"use strict";

var fs = require('fs'),
    S = require('string'),
    ConfigError = require('../utils/error').ConfigError;

module.exports = function (webModule, route, options, cb){
    options = options || {};

    var path = options.path;
    if (!path || !fs.existsSync(path)) {
        return cb('"path" option is required!');
    }

    var maxAge = options.maxAge || 86400000,
        icon; // favicon cache

    cb(null, function (req, res, next){
        if (S(req.url).endsWith('/favicon.ico')) {
            if (icon) {
                res.writeHead(200, icon.headers);
                res.end(icon.body);
            } else {
                fs.readFile(path, function(err, buf){
                    if (err) return next(err);
                    icon = {
                        headers: {
                            'Content-Type': 'image/x-icon'
                            , 'Content-Length': buf.length
                            , 'Cache-Control': 'public, max-age=' + (maxAge / 1000)
                        },
                        body: buf
                    };
                    res.writeHead(200, icon.headers);
                    res.end(icon.body);
                });
            }
        } else {
            next();
        }
    });
};
